package com.eastfair.questionnaire.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.excel.analyze.ExcelAnalyze;
import com.eastfair.core.excel.analyze.ExcelReader;
import com.eastfair.core.excel.bean.ExcelAnalyzeExceptionResult;
import com.eastfair.core.excel.bean.ExcelAnalyzeResult;
import com.eastfair.core.excel.export.ExcelExport;
import com.eastfair.echo.core.EchoService;
import com.eastfair.questionnaire.dto.*;
import com.eastfair.questionnaire.entity.Questionnaire;
import com.eastfair.questionnaire.service.QuestionnaireImportService;
import com.eastfair.questionnaire.service.QuestionnaireService;
import com.eastfair.questionnaire.vo.DynamicQuestionnaireVO;
import com.eastfair.questionnaire.vo.QuestionnaireVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 问卷
 * </p>
 *
 * @author yuwx
 * @date 2021-08-18
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/questionnaire")
@Api(value = "Questionnaire", tags = "问卷")
public class QuestionnaireController extends SuperController<QuestionnaireService, Long, Questionnaire, QuestionnairePageQuery, QuestionnaireSaveDTO, QuestionnaireUpdateDTO> {

    private EchoService echoService;
    private QuestionnaireService questionnaireService;
    private QuestionnaireImportService questionnaireImportService;
    private ExcelReader excelReader;
    @Autowired
    public QuestionnaireController(EchoService echoService, QuestionnaireService questionnaireService, QuestionnaireImportService questionnaireImportService, @Qualifier("urlExcelReader") ExcelReader excelReader) {
        this.echoService = echoService;
        this.questionnaireService = questionnaireService;
        this.questionnaireImportService = questionnaireImportService;
        this.excelReader = excelReader;
    }

    @Override
    public void handlerResult(IPage<Questionnaire> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<Questionnaire> questionnaireList = list.stream().map((map) -> {
            Questionnaire questionnaire = Questionnaire.builder().build();
            //TODO 请在这里完成转换
            return questionnaire;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(questionnaireList));
    }

    @ApiOperation(value = "根据项目Id查询所有问卷", notes = "根据项目Id查询所有问卷")
    @PostMapping("/listAll")
    public R<List<QuestionnaireVO>> listAll() {
        Long projectId = ContextUtil.getProjectId();
        List<QuestionnaireVO> questionnaireVOList = questionnaireService.listAll(projectId);
        return R.success(questionnaireVOList);
    }

    @ApiOperation(value = "获取完整问卷，包含问题，答案，答题结果", notes = "获取完整问卷，包含问题，答案，答题结果")
    @PostMapping("/getCompleteWithAnswerResult")
    public R<QuestionnaireVO> getCompleteWithAnswerResult(
            @RequestBody
            @Validated({QuestionnaireQuery.validateBase.class, QuestionnaireQuery.validateGet.class })
                    QuestionnaireQuery questionnaire) {
        Long projectId = ContextUtil.getProjectId();
        Long questionnaireId = questionnaire.getId();
        QuestionnaireVO questionnaireResult = questionnaireService.getCompleteWithAnswerResult(projectId, questionnaireId, questionnaire.getSubjectType(), questionnaire.getSubjectId());
        return R.success(questionnaireResult);
    }

    @ApiOperation(value = "获取完整问卷，包含问题，答案，答题结果", notes = "获取完整问卷，包含问题，答案，答题结果")
    @PostMapping("/getDynamicWithAnswerResult")
    public R<DynamicQuestionnaireVO> getDynamicWithAnswerResult(
            @RequestBody
            @Validated({QuestionnaireQuery.validateBase.class, QuestionnaireQuery.validateGet.class })
                    QuestionnaireQuery questionnaire) {
        Long projectId = ContextUtil.getProjectId();
        Long questionnaireId = questionnaire.getId();
        DynamicQuestionnaireVO questionnaireResult = questionnaireService.getDynamicWithAnswerResult(projectId, questionnaireId, questionnaire.getSubjectType(), questionnaire.getSubjectId());
        return R.success(questionnaireResult);
    }

    @ApiOperation(value = "保存、修改问卷", notes = "保存问卷")
    @RequestMapping(value = "/save", method = {RequestMethod.POST, RequestMethod.PUT})
    public R<Boolean> save(
            @Validated({QuestionnaireDTO.validateBase.class, QuestionnaireDTO.validateSave.class})
            @RequestBody QuestionnaireDTO questionnaireDTO) {
        Long projectId = ContextUtil.getProjectId();
        questionnaireDTO.setProjectId(projectId);
        questionnaireService.save( questionnaireDTO);
        return R.successDef();
    }

    @ApiOperation(value = "导入问卷", notes = "导入问卷")
    @PostMapping("/importExcel")
    public R<List<ExcelAnalyzeExceptionResult>> importExcel(@RequestBody QuestionnaireImportDTO questionnaireImportDTO) {
        Long projectId = ContextUtil.getProjectId();
        ExcelAnalyze<QuestionnaireExcelDTO> analyze = new ExcelAnalyze<>(excelReader);
        ExcelAnalyzeResult<QuestionnaireExcelDTO> analyzeResult = analyze.analyze(questionnaireImportDTO.getExcelUrl(), QuestionnaireExcelDTO.class);
        if (Objects.isNull(analyzeResult)) {
            return R.success(Collections.emptyList());
        }
        if (!analyzeResult.getSuccess()) {
            return R.success(analyzeResult.getExceptionResult());
        }
        List<QuestionnaireExcelDTO> questionnaireExcelDTOList = analyzeResult.getResultList();
        QuestionnaireExcelResultDTO questionnaireExcelResultDTO = questionnaireImportService.convertQuestionnaire(projectId, questionnaireExcelDTOList);
        questionnaireImportService.batchSave(questionnaireExcelResultDTO);
        return R.success(Collections.emptyList());
    }
    @ApiOperation(value = "问卷导入模版", notes = "问卷导入模版")
    @PostMapping("/excelTemplateExport")
    public void excelTemplateExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("问卷导入模版","UTF-8") + ".xlsx");
        response.addHeader("name", URLEncoder.encode("问卷导入模版","UTF-8") + ".xlsx");
        ExcelExport.export(response.getOutputStream(), QuestionnaireExcelDTO.HEADER, null);

    }
}
